//
//  CocoaWaveAppDelegate.m
//  CocoaWave
//
//  Created by simultech on 16/10/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "CocoaWaveAppDelegate.h"

@implementation CocoaWaveAppDelegate

@synthesize window;
@synthesize waveView;
@synthesize urlLocation;
@synthesize script;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	// Insert code here to initialize your application 
	// work you fucking cocoa app
	//
}

- (void)awakeFromNib {
	NSString *urlText = [NSString stringWithString:@"http://wave.google.com"];
	[[waveView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]];	
	[waveView makeTextLarger:self];
	self.script = [waveView windowScriptObject];
	NSDockTile *tile = [[NSApplication sharedApplication] dockTile];
	[tile setBadgeLabel:@""];
	[NSApp setDelegate:self];
	[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

-(BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
	return YES;
}

-(void) onTimer {
	NSCharacterSet * findLeft = [NSCharacterSet characterSetWithCharactersInString:@"("];
	NSCharacterSet * findRight = [NSCharacterSet characterSetWithCharactersInString:@")"];
	NSString * result = [[self script] evaluateWebScript:@"document.getElementsByTagName('title')[0].innerText"];
	if([result class] != [WebUndefined class]) {
		NSRange leftRange;
		NSRange rightRange;
		leftRange = [result rangeOfCharacterFromSet:findLeft];
		rightRange = [result rangeOfCharacterFromSet:findRight];
		if(leftRange.length > 0 && rightRange.length > 0) {
			result = [[result substringToIndex:rightRange.location] substringFromIndex:leftRange.location+1];
			NSLog(@"%@",result);
			NSDockTile *tile = [[NSApplication sharedApplication] dockTile];
			[tile setBadgeLabel:result];
		} else {
			NSDockTile *tile = [[NSApplication sharedApplication] dockTile];
			[tile setBadgeLabel:@""];
		}
	} else {
		NSDockTile *tile = [[NSApplication sharedApplication] dockTile];
		[tile setBadgeLabel:@""];
	}
}

@end
